<?php
namespace zzcms\util;

/**
 * 加密
 * Class Encryption
 * @package zzcms\util
 */
class Encryption
{
    private static $tmp = '';
    static private $key_code = '458f_$#@$*!fdjisdJDFHUk4%%653154%^@#(FSD#$@0-T';

    /**
     * 解密验证
     */
    static public function decryptSign($post)
    {
        if (!isset($post['timestamp']) || !isset($post['sign'])) {
            self::array2json(['code' => 0, 'msg' => '缺少参数']);
        }
        //验证时间
        if (abs(time() - $post['timestamp']) > 30) {
            self::array2json(['code' => 0, 'msg' => '请求已过期']);
        }
        $data = self::createTokenString($post) . self::$key_code . $post['timestamp'];
        $sign = strtoupper(md5(base64_encode($data)));
        if ($post['sign'] != $sign) {
            self::array2json(['code' => 0, 'msg' => '签名认证错误', 'data' => $data]);
        }
    }

    /**
     * 加密
     */
    static public function encryptSign($post)
    {
        $post['timestamp'] = time();
        $data = self::createTokenString($post) . self::$key_code . $post['timestamp'];
        $post['sign'] = strtoupper(md5(base64_encode($data)));
        return $post;
    }


    /**
     * 解密已加密的用户ID
     */
    static public function decryptUserId()
    {
        $userid = isset($_POST['userid']) ? intval($_POST['userid']) : 0;
        $sign = isset($_POST['sign']) ? trim($_POST['sign']) : '';
        if (empty($userid) || empty($sign)) {
            self::array2json(['code' => 0, 'msg' => '缺少参数']);
        }
        //验证时间
        $timestamp = isset($_POST['timestamp']) ? intval($_POST['timestamp']) : 0;
        if (abs(time() - $timestamp) > 30) {
            self::array2json(['code' => 0, 'msg' => '请求已过期']);
        }
        $data = $userid . self::$key_code . $timestamp;
        $mysign = strtoupper(md5(base64_encode($data)));
        if ($sign != $mysign) {
            self::array2json(['code' => 0, 'msg' => '签名认证错误']);
        }
    }

    /**
     * 加密用户ID
     */
    static public function encryptUserId($userid)
    {
        $timestamp = time();
        $sign = strtoupper(md5(base64_encode($userid . self::$key_code . $timestamp)));
        return ['sign' => $sign, 'timestamp' => $timestamp];
    }

    /**
     * 把数组组成字符串
     * @param $array
     * @return bool|string
     */
    private static function createTokenString($array)
    {
        if (!is_array($array)) {
            return false;
        }
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                self::createTokenString($val);
            } else {
                if ($key == 'sign' || $key == 'timestamp' || strlen($val) < 1) {
                    continue;
                } else {
                    self::$tmp .= $val . ',';
                }
            }
        }
        return rtrim(self::$tmp, ',');
    }

    //把数组转成json字符串
    static private function array2json($array)
    {
        exit(json_encode($array, JSON_UNESCAPED_UNICODE));
    }

}
